package com.fxm.service.impl;

import com.fxm.constant.RedisConstants;
import com.fxm.domain.User;
import com.fxm.returns.RespCode;
import com.fxm.returns.RespEntity;
import com.fxm.service.SignInService;
import com.fxm.service.UserService;
import com.fxm.service.WeChartService;
import com.fxm.service.client.WeChartClientService;
import com.fxm.utils.RedisUtil;
import com.fxm.vo.param.OpenParam;
import com.fxm.vo.param.UserParam;
import com.fxm.vo.result.SessionResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 微信接口 服务实现类
 * </p>
 *
 * @author fxm
 * @since 2020-12-29
 */
@Service
@Slf4j
public class WeChartServiceImpl implements WeChartService {

    @Autowired
    private WeChartClientService weChartClientService;

    @Autowired
    private UserService userService;

    @Autowired
    private SignInService signInService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public RespEntity<SessionResult> getSession(UserParam userParam) {
        if (Objects.isNull(userParam)) {
            log.info("参数为空");
            return new RespEntity(RespCode.PARAMETERS_ERROR);
        }
        SessionResult sessionResult = weChartClientService.getSessionKeyAndOpenId(userParam.getCode());
        if (Objects.isNull(sessionResult)) {
            return new RespEntity(RespCode.SERVER_ERROR);
        }
        RespEntity<User> respEntity = userService.getUserByOpenId(new OpenParam(sessionResult.getOpenid()));
        //当前用户为新用户
        if (Objects.isNull(respEntity.getData())) {
            User user = new User();
            user.setIntegral(0);
            user.setOpenid(sessionResult.getOpenid());
            userService.insertUser(user);
            log.info("新用户登陆，user={}", user);
        }
        //判断今天是否是第一次登陆
        String flag = redisUtil.hget(RedisConstants.key.IS_SIGN, sessionResult.getOpenid());
        flag = StringUtils.isBlank(flag) ? "0" : flag;
        //今日第一次登陆
        if ("0".equals(flag)) {
            //去签到
            signInService.signIn(new OpenParam(sessionResult.getOpenid()));
            //重置答题挑战次数
            resetChallengeNum(sessionResult.getOpenid());
        }
        return new RespEntity(RespCode.SUCCESS, sessionResult);
    }

    /**
     * 重置该用户今日答题挑战次数
     * @param openid
     */
    private void resetChallengeNum(String openid) {
        redisUtil.hset(RedisConstants.key.CHALLENGE_NUM, openid, "3");
    }
}
